package longrise.phone.com.bjjt_jyb.bindinginformation;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.nostra13.universalimageloader.core.ImageLoader;

import longrise.phone.com.bjjt_jyb.Activity.HeNanSurfaceViewCameraActivity;
import longrise.phone.com.bjjt_jyb.Activity.MainActivity;
import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.ApiImpI;
import longrise.phone.com.bjjt_jyb.Utils.CommontUtils;
import longrise.phone.com.bjjt_jyb.Utils.DialogUtils;
import longrise.phone.com.bjjt_jyb.Utils.StringUtils;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;
import longrise.phone.com.bjjt_jyb.View.PromptDialog;


/**
 * 绑定、修改机动车界面
 */
public class BindCarView extends LFView implements View.OnClickListener,
        RadioGroup.OnCheckedChangeListener, MainActivity.OnActivityReturnBitmap {
    private Context context = null;
    private View view = null;
    private TextView titleTV;
    private TextView infoTV;
    private RadioGroup radioGroup;//车型
    private RadioButton smallRBtn;//小型车辆
    private RadioButton bigRBtn;//大型车辆
    private EditText carnumET;
    private EditText framenoET;
    private ImageView driveCardIV;//驾驶证图片
    private TextView deleteTV;
    private Button confirmBtn;

    private EntityBean bean;//数据参数（为null是绑定操作；否则是修改操作）
    private String imageStr;//驾驶证图片的字符流
    private String carType;//车辆类型（0表示小型；1表示大型）
    private BaseApplication application;
    private PromptDialog dialog;
    private Dialog processDialog;

    public BindCarView(Context c, EntityBean bean) {
        super(c);
        this.context = c;
        this.bean = bean;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        setData();
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_bindcar, null);
        //标题栏
        titleTV = (TextView) view.findViewById(R.id.tv_title);
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });
        infoTV = (TextView) view.findViewById(R.id.bcar_tv_info);
        radioGroup = (RadioGroup) view.findViewById(R.id.bcar_rg_type);
        bigRBtn = (RadioButton) view.findViewById(R.id.bcar_rb_big);
        smallRBtn = (RadioButton) view.findViewById(R.id.bcar_rb_small);
        carnumET = (EditText) view.findViewById(R.id.bcar_et_carnum);
        framenoET = (EditText) view.findViewById(R.id.bcar_et_frameno);
        driveCardIV = (ImageView) view.findViewById(R.id.bcar_iv_drivecard);
        deleteTV = (TextView) view.findViewById(R.id.bcar_tv_delete);
        confirmBtn = (Button) view.findViewById(R.id.bcar_btn_confirm);
    }

    private void regEvent(boolean b) {
        if (null != driveCardIV) {
            driveCardIV.setOnClickListener(b ? this : null);
        }
        if (null != confirmBtn) {
            confirmBtn.setOnClickListener(b ? this : null);
        }
        if (null != radioGroup) {
            radioGroup.setOnCheckedChangeListener(b ? this : null);
        }
        if (null != deleteTV) {
            deleteTV.setOnClickListener(b ? this : null);
        }
    }

    public void setData() {
        if (null == bean) {//绑定操作
            titleTV.setText("绑定机动车");
//            infoTV.setText("请输入车辆信息");
            confirmBtn.setText("绑定");
            deleteTV.setVisibility(View.GONE);
        } else {
            titleTV.setText("修改车辆信息");
//            infoTV.setText("请修改车辆信息");
            confirmBtn.setText("确认修改");
            deleteTV.setVisibility(View.VISIBLE);
            //设置参数
            //车型
            carType = bean.getString("cartype");
            if (TextUtils.equals(carType, "2")) {
                bigRBtn.setChecked(true);
            } else {
                smallRBtn.setChecked(true);
            }
            //车牌
            String carnum = bean.getString("carno");
            if (!TextUtils.isEmpty(carnum)) {
                carnumET.setText(carnum);
            }
            //车架号
            String frameno = bean.getString("identificationnum");
            if (!TextUtils.isEmpty(frameno)) {
                framenoET.setText(frameno);
            }
            //行车证照片
            String pic = bean.getString("drivingnoimg");
            if (!TextUtils.isEmpty(pic)) {
                ImageLoader.getInstance().displayImage(pic, driveCardIV, CommontUtils.getOptions());
                imageStr = pic;//网络图片则保存图片路径
            }
        }
        application = (BaseApplication) context.getApplicationContext();
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.bcar_iv_drivecard://拍摄驾驶证
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt("backGroundResourceId",R.mipmap.xinjiang_xsz);
                    intent.putExtras(bundle);
                    intent.setClass(context, HeNanSurfaceViewCameraActivity.class);
                    ((Activity) context).startActivityForResult(intent, 99);
                    break;
                case R.id.bcar_btn_confirm://确定
                    confirmModify();
                    break;
                case R.id.bcar_tv_delete://删除车辆
                    showDeleteDialog();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.bcar_rb_big://大型
                carType = "2";
                break;
            case R.id.bcar_rb_small://小型
                carType = "1";
                break;
            default:
                break;
        }
    }

    //显示删除对话框
    private void showDeleteDialog() {
        if (null == dialog) {
            dialog = new PromptDialog(context);
            dialog.setIcon(R.mipmap.warn);
            dialog.setCancel("返回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setConfirm("删除", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    deleteCar();
                }
            });
            //说明信息
            String carnum = bean.getString("carno");
            String info = "确定删除:" + carnum;
            String[] strs = new String[]{carnum};
            int[] colors = new int[]{Color.parseColor("#ff6666")};
            dialog.setInfo(CommontUtils.changeStrColor(info, strs, colors));
        }
        dialog.show();
    }

    /**
     * 删除车辆
     */
    private void deleteCar() {
        DialogUtils.showDialog(context);
        String carId = bean.getString("id");
        String userflag = application.getKckpName();
        String token = application.getToken();
        ApiImpI.getInstance(application).deleteCar(carId, userflag, token, callBack);
    }

    /**
     * 绑定或确认修改
     */
    private void confirmModify() throws Exception {
        if (TextUtils.isEmpty(carType)) {
            UiUtil.showToast(context, "请选择车型");
            return;
        }
        String carnum = carnumET.getText().toString().trim();
        if (!StringUtils.isCar(carnum)) {
            UiUtil.showToast(context, "请输入合法的车牌号码");
            return;
        }
        String frameno = framenoET.getText().toString().trim();
        if (TextUtils.isEmpty(frameno)) {
            UiUtil.showToast(context, "请输入车架号");
            return;
        }
        if (TextUtils.isEmpty(imageStr)) {
            UiUtil.showToast(context, "请拍摄行车证照片");
            return;
        }
        String token = application.getToken();
        String userflag = application.getKckpName();
        DialogUtils.showDialog(context);
        if (null == bean) {
            ApiImpI.getInstance(application).addAcccarhen(carType, carnum, frameno, imageStr,
                    userflag, token, callBack);
        } else {
            String carId = bean.getString("id");
            ApiImpI.getInstance(application).modifyCar(carId, userflag, carnum, frameno,
                    carType, token, imageStr, callBack);
        }
    }

    private ApiImpI.RequestCallBack callBack = new ApiImpI.RequestCallBack() {
        @Override
        public void onError(String error) {
            DialogUtils.closeDialog();
            if (!TextUtils.isEmpty(error)) {
                UiUtil.showToast(getContext(), error);
            }
        }

        @Override
        public void onSuccess(Object result) {
            DialogUtils.closeDialog();
            EntityBean bean = (EntityBean) result;
            String redes = bean.getString("redes");
            if (!TextUtils.isEmpty(redes)) {
                UiUtil.showToast(getContext(), redes);
            }
            String restate = bean.getString("restate");
            if (TextUtils.equals("1", restate)) {
                LSMsgCall(99, "bindinfo");
                OnDestroy();
                closeForm();
            }
        }
    };

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        regEvent(false);
        dialog = null;
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode, Intent data) {
        if (requestCode == 99 && resultCode == HeNanSurfaceViewCameraActivity.RESULT_OK) {
            String path = data.getStringExtra("image");
            if (TextUtils.isEmpty(path)) {
                UiUtil.showToast(context, "拍照图片有误，请重新拍照！");
                return;
            }
            String imgpath = "file:///" + path;
            ImageLoader.getInstance().displayImage(imgpath, driveCardIV, CommontUtils.getOptions());
            //图片转成bitmap
            processDialog = UiUtil.showProcessDialog(context, "正在识别...");
            Bitmap imgeBitmap = BitmapFactory.decodeFile(path);
            //imageStr = FileUtils.File2byte(new File(path), true);
            ApiImpI.getInstance(application).picIdentification(CommontUtils.Bitmap2Bytes(imgeBitmap), "6", callBack2);
        }
    }

    private ApiImpI.RequestCallBack callBack2 = new ApiImpI.RequestCallBack() {
        @Override
        public void onError(String error) {
            if (null != processDialog) {
                if (processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
        }

        @Override
        public void onSuccess(Object result) {
            if (null != processDialog) {
                if (processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
            EntityBean bean = (EntityBean) result;
            String restate = bean.getString("restate");
            String redes = bean.getString("redes");
            if ("1".equals(restate)) {
                //图像识别成功，将内容填充到界面
                EntityBean dataBean = ((EntityBean) result).getBean("data");
                if (null != bean) {
                    imageStr = dataBean.getString("photo");
                    EntityBean imageBean = dataBean.getBean("imgdata");
                    if (null != imageBean) {
                        String carno = imageBean.getString("carno");//车牌号
                        String vin = imageBean.getString("vin");//车架号
                        carnumET.setText(carno);
                        framenoET.setText(vin);
                    } else {
                        UiUtil.showToast(context, "图像识别失败，请重新拍照或者手动填写");
                    }
                }
            } else {
                UiUtil.showToast(context, redes);
            }

        }
    };
}